//
//  DLModifyPasswordVC.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/12/27.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLModifyPasswordVC.h"
#import "DLTFView.h"

@interface DLModifyPasswordVC ()

@property (nonatomic, strong) DLTFView *originTF;

@property (nonatomic, strong) DLTFView *currentPasswordTF;

@property (nonatomic, strong) DLTFView *confirmCurrentPasswordTF;

@end

@implementation DLModifyPasswordVC


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNav];
    [self layoutSubControls];
    // Do any additional setup after loading the view.
}
- (void) layoutSubControls {
    
    CGFloat registBtnWidth = kAutoWidth(340);
    CGFloat leftMargin = (kScreenWidth - registBtnWidth) / 2;
    
    DLTFView *originTF = [[DLTFView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 90) andTitle:@"原密码" andPlaceHolder:@"请输入原密码"];
    [self.view addSubview:originTF];
    self.originTF = originTF;
    
    DLTFView *currentPasswordTF = [[DLTFView alloc] initWithFrame:CGRectMake(originTF.left, originTF.bottom, kScreenWidth, 90) andTitle:@"新密码" andPlaceHolder:@"请输入6-16位新密码"];
    [self.view addSubview:currentPasswordTF];
    self.currentPasswordTF = currentPasswordTF;
    
    DLTFView *confirmCurrentPasswordTF = [[DLTFView alloc] initWithFrame:CGRectMake(currentPasswordTF.left, currentPasswordTF.bottom, kScreenWidth, 90) andTitle:@"确认新密码" andPlaceHolder:@"确认新密码"];
    [self.view addSubview:confirmCurrentPasswordTF];
    self.confirmCurrentPasswordTF = confirmCurrentPasswordTF;
    
    UIButton *submitBtn = [UIButton buttonWithType:0];
    submitBtn.frame = CGRectMake(leftMargin, confirmCurrentPasswordTF.bottom + 75, registBtnWidth, 44);
    submitBtn.layer.cornerRadius = 4;
    submitBtn.clipsToBounds = YES;
    submitBtn.backgroundColor = kDLBtnNormalBgColor;
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    submitBtn.titleLabel.font = kSystemFont(14);
    [submitBtn addTarget:self action:@selector(submitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submitBtn];
}

- (void) submitBtnClick:(UIButton *)btn {
    
    if (self.originTF.inputTF.text.length < 6) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"原密码长度不正确" duration:1 position:CSToastPositionCenter];
        return;
    }
    
    if (self.currentPasswordTF.inputTF.text.length < 6) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"新密码长度不正确" duration:1 position:CSToastPositionCenter];
        
        return;
    }
    
    if (![self.confirmCurrentPasswordTF.inputTF.text isEqualToString:self.currentPasswordTF.inputTF.text]) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"确认密码和新密码不一致" duration:1 position:CSToastPositionCenter];
        
        return;
    }
    
    [self submitAction];
}
- (void) submitAction {
    //接口
    NSString *postUrl = HTTPModifyPassword;
    NSString *md5PasswordOld = [self.originTF.inputTF.text md5Hash];
    NSString *md5PasswordFresh = [self.currentPasswordTF.inputTF.text md5Hash];
    NSDictionary *postDic = @{
                              @"oldpwd" : md5PasswordOld,
                              @"newpwd" : md5PasswordFresh
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
            //修改成功
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            [self.navigationController popToRootViewControllerAnimated:YES];
            kuserManager.isLogin = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                kuserManager.lastVc.tabBarController.selectedIndex = 0;
                [kuserManager userLogin];
            });
        } else if ([[responseObject objectForKey:@"code"] intValue] == 500){
            //原密码不正确
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            [self.view endEditing:YES];
            [self.originTF.inputTF becomeFirstResponder];
            
        } else if ([[responseObject objectForKey:@"code"] intValue] == 501){
            //用户信息失效
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            [self.navigationController popToRootViewControllerAnimated:YES];
            kuserManager.isLogin = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                kuserManager.lastVc.tabBarController.selectedIndex = 0;
                [kuserManager userLogin];
            });
        } else {
            //其他
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
        }
        
        
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].enable = NO;
    
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.translucent = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ConfirmCurrentPasswordTFBecomeFirstResponder) name:@"TFBecomeFirstResponder" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ConfirmCurrentPasswordTFResignFirstResponder) name:@"TFResignFirstResponder" object:nil];
}
- (void) ConfirmCurrentPasswordTFResignFirstResponder {
    [UIView animateWithDuration:0.25 animations:^{
        [self.view resetY:kHeightNavigation];
    }];
}
- (void) ConfirmCurrentPasswordTFBecomeFirstResponder {
    [UIView animateWithDuration:0.25 animations:^{
        [self.view resetY:-kHeightNavigation];
    }];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void) setUpNav {
    
    self.titleView.title = @"修改登录密码";
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
